package com.example.tangjiangxu.contactsgroupdemo;

import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.SectionIndexer;
import android.widget.TextView;

import java.util.List;

/**
 * Created by tangjiangxu on 3/14/17.
 */

public class ContactAdapter extends ArrayAdapter<Contact>{
    private static final String TAG = "ContactAdapter";

    /** 需要渲染的item的布局 **/
    private int resourceId;

    /** 字母标分组工具 **/
    private SectionIndexer mIndexer;

    public ContactAdapter(Context context, int resourceId, List<Contact> objects) {
        super(context, resourceId, objects);
        this.resourceId = resourceId;
    }

    @NonNull
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Contact contact = getItem(position);
        View view = null;
        if (convertView == null) {
            view = LayoutInflater.from(getContext()).inflate(resourceId, null);
        } else {
            view = convertView;
        }
        TextView tvSortKey = (TextView) view.findViewById(R.id.tv_title);
        LinearLayout lLSortKey = (LinearLayout) view.findViewById(R.id.ll_title);
        TextView tvName = (TextView) view.findViewById(R.id.tv_name);
        tvName.setText(contact.getName());
        // 当前位置所在的分组, 例如＃-0,A-1,B-2...
        int section = mIndexer.getSectionForPosition(position);
        //当前分组所在的位置，即当前分组的第一个条目，例如＃－0，A-5,B-10...
        int curFirstPosition = mIndexer.getPositionForSection(section);
        //Log.e(TAG, "getView name:" + contact.getName() +",section:" + section + ",sortKey:" + contact.getSortKey() + ",curFirstPosition:" + curFirstPosition);
        //当前条目，是该分组当第一个条目时，让其显示sortkey，当前分组的其他条目不显示sortkey
        if (position == curFirstPosition) {
            tvSortKey.setText(contact.getSortKey());
            lLSortKey.setVisibility(View.VISIBLE);
        } else {
            lLSortKey.setVisibility(View.GONE);
        }

        return view;
    }

    /**
     * 给当前适配器传入一个分组工具
     */
    public void setIndexer(SectionIndexer indexer) {
        this.mIndexer = indexer;
    }
}
